

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 1. 贪吃蛇介绍 贪吃蛇游戏想必大家并不陌生，它的玩法很简单，通过上下左右控制贪吃蛇的移动，让它吃到地图上某个位置的食物，每次吃到食物，小蛇就会变长一段，看起来是不是很神奇呢！其实这个游戏的设计原理十分简单，通过本篇文章你可以学会使用C语言设计简单的贪吃蛇小游戏。在学习之前你只需要有以下知识的基础：  C语言基础：基本数据类型、循环语句、switch 条件语句，宏定义，struct">
<meta property="og:type" content="article">
<meta property="og:title" content="C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析">
<meta property="og:url" content="http://example.com/2022/08/21/C%E8%AF%AD%E8%A8%80%20%E5%AE%9E%E7%8E%B0%E8%B4%AA%E5%90%83%E8%9B%87%20_%20%E5%8D%81%E5%88%86%E9%92%9F%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B%20_%20%E5%88%9D%E5%AD%A6%E8%80%85%E6%A1%88%E4%BE%8B%20_%20%E9%99%84%E5%B8%A6%E8%AE%BE%E8%AE%A1%E6%80%9D%E8%B7%AF%20+%20%E4%BB%A3%E7%A0%81%20+%20%E5%9B%BE%E6%96%87%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 1. 贪吃蛇介绍 贪吃蛇游戏想必大家并不陌生，它的玩法很简单，通过上下左右控制贪吃蛇的移动，让它吃到地图上某个位置的食物，每次吃到食物，小蛇就会变长一段，看起来是不是很神奇呢！其实这个游戏的设计原理十分简单，通过本篇文章你可以学会使用C语言设计简单的贪吃蛇小游戏。在学习之前你只需要有以下知识的基础：  C语言基础：基本数据类型、循环语句、switch 条件语句，宏定义，struct">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/351a42290b4e41388962cab6e10b8231.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/650540de7dd746a8968658c816b739ae.gif#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/12447c1499fc46108a9a1aa1a1530e47.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2fbce3cf85d241d4aaec88508c76847f.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/452a6a68304e4b80b74a8da263647221.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/631ae04212ef4349a53797877cca227e.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/0f06f599f5f94f5e91b0c3527a0aa487.gif#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/7c19d1943e7e9868895982e1d407c598.jpeg">
<meta property="og:image" content="https://img-blog.csdnimg.cn/09d16d4b89a6499da84a63f5d2db1f0d.gif#pic_center">
<meta property="article:published_time" content="2022-08-20T16:35:52.000Z">
<meta property="article:modified_time" content="2022-08-22T15:42:45.217Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="C语言小游戏">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/351a42290b4e41388962cab6e10b8231.png">
  
  
  
  <title>C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-08-21 00:35" pubdate>
          2022年8月21日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          7.1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          60 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p><img src="https://img-blog.csdnimg.cn/351a42290b4e41388962cab6e10b8231.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>@[toc]</p>
<h1 id="1-贪吃蛇介绍"><a href="#1-贪吃蛇介绍" class="headerlink" title="1. 贪吃蛇介绍"></a>1. 贪吃蛇介绍</h1><hr>
<p>贪吃蛇游戏想必大家并不陌生，它的玩法很简单，通过上下左右控制贪吃蛇的移动，让它吃到地图上某个位置的食物，每次吃到食物，小蛇就会变长一段，看起来是不是很神奇呢！其实这个游戏的设计原理十分简单，通过本篇文章你可以学会使用C语言设计简单的贪吃蛇小游戏。在学习之前你只需要有以下知识的基础：</p>
<ol>
<li>C语言基础：基本数据类型、循环语句、switch 条件语句，宏定义，struct 结构体，函数的定义与使用</li>
<li>DevCpp 工具的基本使用：编译 和运行 .c 文件</li>
</ol>
<p>如果你有以上这些基础，我相信只需要10分钟你就能掌握贪吃蛇小游戏的编写技巧。</p>
<p><img src="https://img-blog.csdnimg.cn/650540de7dd746a8968658c816b739ae.gif#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>如上图所示，这个小游戏最主要的两个部分就是 <strong>画面</strong> 和 <strong>操作</strong>。<br>首先，小游戏绘制出了一个范围表示贪吃蛇允许的运动范围，以及不断运动着的小蛇。<br>其次，通过画面我们可以通过键盘来操作小蛇的方向，在这个画面中主要有 上、下、左、右 四种方向。</p>
<p>在写游戏代码前，我们有必要先了解一下如何用 C语言来实现小游戏的画面以及获取用户的操作。</p>
<h1 id="2-前置准备"><a href="#2-前置准备" class="headerlink" title="2. 前置准备"></a>2. 前置准备</h1><hr>
<h2 id="2-1-C语言移动光标"><a href="#2-1-C语言移动光标" class="headerlink" title="2.1 C语言移动光标"></a>2.1 C语言移动光标</h2><p>windows.h 头文件支持许多与 Windows 系统相关的功能，这里我们主要是使用它里面当中可以获取运行的窗口，运行的坐标相关的方法。<br>参考：<a target="_blank" rel="noopener" href="https://docs.microsoft.com/zh-cn/windows/console/setconsolecursorposition">https://docs.microsoft.com/zh-cn/windows/console/setconsolecursorposition</a></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;windows.h&gt;</span></span><br><br><span class="hljs-comment">/*--------------------移动光标--------------------- */</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">gotoxy</span><span class="hljs-params">(<span class="hljs-type">int</span> x,<span class="hljs-type">int</span> y)</span> <br>&#123;<br>    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);  <span class="hljs-comment">// 获取当前运行程序的窗口 </span><br><br>    COORD coord;									  <span class="hljs-comment">// 获取光标 </span><br>   <br>    coord.X = x;									  <span class="hljs-comment">// 设置坐标					</span><br>    coord.Y = y;	<br>    <br>    SetConsoleCursorPosition(handle,coord);			  <span class="hljs-comment">// 设置指定控制台屏幕缓冲区中的光标位置。 </span><br>&#125;	<br></code></pre></td></tr></table></figure>

<p>测试：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdio.h&gt;</span></span><br><br><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">()</span><br>&#123;<br>	gotoxy(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>);<br>	<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;hello&quot;</span>);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>运行结果：<br><img src="https://img-blog.csdnimg.cn/12447c1499fc46108a9a1aa1a1530e47.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-2-C语言读取键盘按键"><a href="#2-2-C语言读取键盘按键" class="headerlink" title="2.2 C语言读取键盘按键"></a>2.2 C语言读取键盘按键</h2><p>读取用户的键盘按键则通过 conio.h 这个头文件，它的 _kbhit() 方法 判断用户是否按下某个键，它的最大特点是：如果用户没有按下任何按键，则会返回 false，若按下了按键则返回 true， 同时需配合 _getch() 函数来获取到用户之前按下的键对应的 ASCII码。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;conio.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdio.h&gt;</span></span><br><span class="hljs-comment">/* ---获取用户按键--- */</span><br><span class="hljs-type">int</span> <span class="hljs-title function_">keyDown</span><span class="hljs-params">()</span><br>&#123;	<span class="hljs-type">int</span> key = <span class="hljs-number">-1</span>;<br>    <span class="hljs-keyword">if</span>(_kbhit())<br>    &#123;<br>    	fflush(<span class="hljs-built_in">stdin</span>);		<span class="hljs-comment">// 刷新控制台输入的缓冲区</span><br>    	key=_getch();	    <span class="hljs-comment">// 读取键盘的按键</span><br>    &#125;<br>    <span class="hljs-keyword">return</span> key;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">()</span>&#123;<br>	<span class="hljs-type">int</span> key = <span class="hljs-number">0</span>; <br>	<span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>)&#123;<br>		key = keyDown();	<span class="hljs-comment">// 读取用户的键盘按键, 若没有则执行下一行内容</span><br>		<span class="hljs-keyword">if</span>(key != <span class="hljs-number">-1</span>)<br>			<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;按下的按键为: %c\n&quot;</span>, <span class="hljs-type">char</span>(key)); <br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>运行结果：<br><img src="https://img-blog.csdnimg.cn/2fbce3cf85d241d4aaec88508c76847f.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-3-C语言延迟生成随机数"><a href="#2-3-C语言延迟生成随机数" class="headerlink" title="2.3 C语言延迟生成随机数"></a>2.3 C语言延迟生成随机数</h2><p>在游戏过程中，我们发现食物的位置每次都是随机的，所以我们需要有生成随机数的函数。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;time.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdlib.h&gt;</span></span><br><span class="hljs-comment">/*--------获取 [a, b) 范围的随机整数------*/</span><br><span class="hljs-type">int</span> <span class="hljs-title function_">randomIn</span><span class="hljs-params">(<span class="hljs-type">int</span> a, <span class="hljs-type">int</span> b)</span>&#123;<br>    srand((<span class="hljs-type">unsigned</span> <span class="hljs-type">int</span>)time(<span class="hljs-literal">NULL</span>));<br>	<span class="hljs-keyword">return</span> rand() % b + a;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>测试：（ 输出10次 [0, 10） 的随机整数 ）</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;time.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdio.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdlib.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;windows.h&gt;</span></span><br><span class="hljs-comment">/*--------获取 [a, b) 范围的随机整数------*/</span><br><span class="hljs-type">int</span> <span class="hljs-title function_">randomIn</span><span class="hljs-params">(<span class="hljs-type">int</span> a, <span class="hljs-type">int</span> b)</span>&#123;<br>    srand((<span class="hljs-type">unsigned</span> <span class="hljs-type">int</span>)time(<span class="hljs-literal">NULL</span>));<br>	<span class="hljs-keyword">return</span> rand() % b + a;<br>&#125;<br><br><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">()</span>&#123;<br>	<span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++)&#123;<br>		Sleep(<span class="hljs-number">1000</span>);					<span class="hljs-comment">// 延迟 1秒</span><br>    	<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;第 %d 个随机数 : %d\n&quot;</span> , i+<span class="hljs-number">1</span>, randomIn(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>));<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>运行效果：<br><img src="https://img-blog.csdnimg.cn/452a6a68304e4b80b74a8da263647221.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-4-C语言隐藏光标"><a href="#2-4-C语言隐藏光标" class="headerlink" title="2.4 C语言隐藏光标"></a>2.4 C语言隐藏光标</h2><p>为了防止游戏不断闪烁干扰实现，我们需要调用 API 来实现控制台窗口隐藏光标</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/*-------------------- 隐藏光标 -------------------- */</span> <br><span class="hljs-type">void</span> <span class="hljs-title function_">hideCursor</span><span class="hljs-params">()</span><br>&#123;<br>	CONSOLE_CURSOR_INFO cursor;    <br>	cursor.bVisible = FALSE;    <br>	cursor.dwSize = <span class="hljs-keyword">sizeof</span>(cursor);    <br>	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);    <br>	SetConsoleCursorInfo(handle, &amp;cursor);<br>&#125;<br></code></pre></td></tr></table></figure>
<h1 id="3-实现贪吃蛇小游戏"><a href="#3-实现贪吃蛇小游戏" class="headerlink" title="3. 实现贪吃蛇小游戏"></a>3. 实现贪吃蛇小游戏</h1><h2 id="3-1-绘制游戏边界"><a href="#3-1-绘制游戏边界" class="headerlink" title="3.1 绘制游戏边界"></a>3.1 绘制游戏边界</h2><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> MAP_HEIGHT 25					</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> MAP_WIDTH 60</span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> WALL <span class="hljs-string">&quot;■&quot;</span></span><br><span class="hljs-comment">/*----------------绘制地图------------- */</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">drawMap</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-comment">// 绘制左右边界</span><br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;i&lt;=MAP_HEIGHT;i++)		<span class="hljs-comment">// 遍历指定的地图高度</span><br>    &#123;<br>        gotoxy(<span class="hljs-number">0</span>,i);					<span class="hljs-comment">// 将光标移动到边界最左边的位置</span><br>        <span class="hljs-built_in">printf</span>(WALL);<br>        gotoxy(MAP_WIDTH,i);			<span class="hljs-comment">// 将光标移动到边界最右边的位置</span><br>        <span class="hljs-built_in">printf</span>(WALL);<br>    &#125;<br>	<span class="hljs-comment">// 绘制上下边界</span><br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;i&lt;=MAP_WIDTH;i+=<span class="hljs-number">2</span>) 		<span class="hljs-comment">// 遍历指定的地图宽度</span><br>    &#123;									<span class="hljs-comment">// 由于 ■ 符号在水平方向上是占两个字符的， 所以地图也相应的隔两个位置</span><br>        gotoxy(i,<span class="hljs-number">0</span>);					<span class="hljs-comment">// 将光标移动到边界最上边的位置</span><br>        <span class="hljs-built_in">printf</span>(WALL);<br>        gotoxy(i,MAP_HEIGHT);<br>        <span class="hljs-built_in">printf</span>(WALL);					<span class="hljs-comment">// 将光标移动到边界最下边的位置</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>运行结果：<br><img src="https://img-blog.csdnimg.cn/631ae04212ef4349a53797877cca227e.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="3-2-绘制小蛇"><a href="#3-2-绘制小蛇" class="headerlink" title="3.2 绘制小蛇"></a>3.2 绘制小蛇</h2><p>在绘制小蛇以前我们要知道它有哪些属性：</p>
<ul>
<li>蛇的长度</li>
<li>蛇的移动速度</li>
<li>蛇头和蛇身的位置（横坐标, 纵坐标）</li>
</ul>
<p>我们可以用 struct 结构体来表示蛇的结构</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> SNAKE_SIZE 100  <span class="hljs-comment">// 蛇头加上蛇身的最大节数</span></span><br><span class="hljs-class"><span class="hljs-keyword">struct</span></span><br><span class="hljs-class">&#123;</span> <br>	<span class="hljs-type">int</span> x[SNAKE_SIZE];	<span class="hljs-comment">// 蛇头和蛇身的横坐标</span><br>	<span class="hljs-type">int</span> y[SNAKE_SIZE];  <span class="hljs-comment">// 蛇头和蛇身的纵坐标</span><br>	<span class="hljs-type">int</span> len; 			<span class="hljs-comment">// 蛇长</span><br>	<span class="hljs-type">int</span> speed; 			<span class="hljs-comment">// 移动速度</span><br>    <span class="hljs-type">int</span> direction;		<span class="hljs-comment">// 移动方向</span><br>&#125; snake;<br></code></pre></td></tr></table></figure>

<p>接下来我们定义绘制小蛇的函数，和之前绘制边界的思路类似，先移动光标，然后再printf 打印</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> SNAKE <span class="hljs-string">&quot;■&quot;</span></span><br><span class="hljs-comment">/* ----------- 绘制小蛇 -------------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">drawSnake</span><span class="hljs-params">()</span>&#123;<br>	<span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;i &lt; snake.len; i++)<br>    &#123;<br>        gotoxy(snake.x[i],snake.y[i]);<br>        <span class="hljs-built_in">printf</span>(SNAKE);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="3-3-擦除小蛇尾部"><a href="#3-3-擦除小蛇尾部" class="headerlink" title="3.3 擦除小蛇尾部"></a>3.3 擦除小蛇尾部</h2><p>根据之前移动小蛇的分析，我们知道在小蛇移动后，它的尾巴是需要抹去的，否则小蛇在移动的时候身子就会越来越长，这里为方便之后调用，定义可以擦除游戏画面的函数。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/*------------------ 擦除画面 --------------------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">clear</span><span class="hljs-params">(<span class="hljs-type">int</span> x, <span class="hljs-type">int</span> y)</span><br>&#123;<br>    gotoxy(x, y);<br>    <span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;  &quot;</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="3-4-绘制食物"><a href="#3-4-绘制食物" class="headerlink" title="3.4 绘制食物"></a>3.4 绘制食物</h2><p>和绘制小蛇类似，我们先定义一个表示食物的结构体：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-class"><span class="hljs-keyword">struct</span></span><br><span class="hljs-class">&#123;</span><br>	<span class="hljs-type">int</span> x;<br>	<span class="hljs-type">int</span> y;<br>&#125;food;<br></code></pre></td></tr></table></figure>
<p>在本次小游戏的设计中，食物只有一个，所以就不需要以数组的形式存储了。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> FOOD <span class="hljs-string">&quot;●&quot;</span></span><br><span class="hljs-comment">/*----------绘制食物----------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">drawFood</span><span class="hljs-params">()</span>&#123;<br>	gotoxy(food.x, food.y);<br>    <span class="hljs-built_in">printf</span>(FOOD);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在绘制食物时，我们需要考虑绘制的位置，食物的位置是随机的，但是不能在小蛇的蛇头或者蛇身上。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/*------------ 判断坐标是否在蛇头或蛇身上--------------*/</span><br><span class="hljs-type">bool</span> <span class="hljs-title function_">isInSnake</span><span class="hljs-params">(<span class="hljs-type">int</span> x,<span class="hljs-type">int</span> y)</span>&#123;<br>	<span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; snake.len; i++)<br>    	<span class="hljs-keyword">if</span>(snake.x[i] == x &amp;&amp; snake.y[i] == y)<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>&#125;<br><br><span class="hljs-comment">/*------------ 随机生成食物的位置 --------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">randomFoodPosition</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-keyword">do</span> &#123;<br>    	food.x = randomIn(<span class="hljs-number">2</span>, MAP_WIDTH - <span class="hljs-number">4</span>);		<span class="hljs-comment">// 食物在水平方向上必须在围墙内</span><br>        <br>        food.y = randomIn(<span class="hljs-number">1</span>, MAP_HEIGHT - <span class="hljs-number">2</span>);		<span class="hljs-comment">// 食物在竖直方向上必须在围墙内</span><br>    <br>    &#125; <span class="hljs-keyword">while</span>(isInSnake(food.x, food.y) || food.x % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>);		    <span class="hljs-comment">// 当坐标不合理时, 则重新生成</span><br>&#125;<br><br><br></code></pre></td></tr></table></figure>
<h2 id="3-5-移动小蛇"><a href="#3-5-移动小蛇" class="headerlink" title="3.5 移动小蛇"></a>3.5 移动小蛇</h2><p>移动小蛇是有规律的，我们再次观察之前的动态图：<br><img src="https://img-blog.csdnimg.cn/0f06f599f5f94f5e91b0c3527a0aa487.gif#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>蛇头用于控制方向，如果用户没有按下任何键，那么小蛇会一直往那个方向前进，在移动过程中，蛇身的每一节总会往它靠近蛇头的那一节蛇身移动。<br><img src="https://img-blog.csdnimg.cn/img_convert/7c19d1943e7e9868895982e1d407c598.jpeg" srcset="/img/loading.gif" lazyload></p>
<p>通过上面的分析，我们将 蛇头 和 蛇身 分开考虑：</p>
<ul>
<li>蛇头：根据移动方向移动，比如向右，那么就向右移动一格</li>
<li>蛇身：当前这节蛇身朝着移动前靠近蛇头的那一节蛇身的位置移动，直接替换位置即可</li>
</ul>
<p>除了绘制小蛇移动后的画面以外，我们还需要擦除它之前的尾巴，这个直接移动光标到之前尾巴的部分，printf 打印两个空格即可。在控制台中，光标的移动规律是如下图所示的，通过这个规律我们能总结出对于坐标 (x, y) ，它的上下左右四个坐标的特点：</p>
<ul>
<li>上 ( x, y -1 )</li>
<li>下 ( x, y + 1)</li>
<li>左 ( x - 1, y ) </li>
<li>右 ( x + 1, y )</li>
</ul>
<p>![](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/img_convert/09f5a1e2b50c57dcd62bd40593302bdb.jpeg#">https://img-blog.csdnimg.cn/img_convert/09f5a1e2b50c57dcd62bd40593302bdb.jpeg#</a> &#x3D;30%x)</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> D_UP <span class="hljs-string">&#x27;w&#x27;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> D_RIGHT <span class="hljs-string">&#x27;d&#x27;</span> </span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> D_DOWN <span class="hljs-string">&#x27;s&#x27;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> D_LEFT <span class="hljs-string">&#x27;a&#x27;</span></span><br><br><span class="hljs-comment">/*----------移动小蛇 --------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">move</span><span class="hljs-params">()</span>&#123;<br>	clear(snake.x[snake.len - <span class="hljs-number">1</span>], snake.y[snake.len <span class="hljs-number">-1</span>]);<br>    <span class="hljs-comment">// 先移动蛇身</span><br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = snake.len - <span class="hljs-number">1</span>; i &gt; <span class="hljs-number">0</span> ; i--)&#123;<br>    	snake.x[i] = snake.x[i<span class="hljs-number">-1</span>] + <span class="hljs-number">2</span>;<br>        snake.y[i] = snake.y[i<span class="hljs-number">-1</span>];<br>    &#125;<br>    <span class="hljs-comment">// 控制蛇头</span><br>	<span class="hljs-keyword">switch</span> (snake.direction)&#123;<br>        <span class="hljs-keyword">case</span> UP:<br>            snake.y[<span class="hljs-number">0</span>]--;<br>            <span class="hljs-keyword">break</span>;<br>        <span class="hljs-keyword">case</span> DOWN:<br>            snake.y[<span class="hljs-number">0</span>]++;<br>            <span class="hljs-keyword">break</span>;<br>        <span class="hljs-keyword">case</span> LEFT:<br>            snake.x[<span class="hljs-number">0</span>] -= <span class="hljs-number">2</span>;<br>            <span class="hljs-keyword">break</span>;<br>        <span class="hljs-keyword">case</span> RIGHT:<br>            snake.x[<span class="hljs-number">0</span>] += <span class="hljs-number">2</span>;<br>            <span class="hljs-keyword">break</span>;   <br>    &#125;<br>    drawSnake();<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id=""><a href="#" class="headerlink" title=""></a></h2><h2 id="3-6-小蛇吃到食物"><a href="#3-6-小蛇吃到食物" class="headerlink" title="3.6 小蛇吃到食物"></a>3.6 小蛇吃到食物</h2><p>当蛇头遇到食物时，小蛇吃到了食物，此时小蛇的身体会长一节，这里的实现比较简单，我们只要将小蛇的身体整体往后移动一节即可。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/*--------------  判断是否吃到食物 --------------*/</span><br><span class="hljs-type">bool</span> <span class="hljs-title function_">isEating</span><span class="hljs-params">()</span>&#123;<br>	<span class="hljs-keyword">return</span> snake.x[<span class="hljs-number">0</span>] == food.x &amp;&amp; snake.y[<span class="hljs-number">0</span>] == food.y;<br>&#125;<br><span class="hljs-comment">/*---------------  小蛇吃到食物 ----------------*/</span><br><span class="hljs-type">bool</span> <span class="hljs-title function_">snakeEatenFood</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-keyword">if</span>(isEating())&#123;<br>        <span class="hljs-comment">// 蛇的身体 + 1</span><br>        snake.len ++;<br>        <span class="hljs-keyword">if</span>(snake.len &lt; SNAKE_SIZE) &#123;		<span class="hljs-comment">// 若蛇还未达到最大长度</span><br>			<span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = snake.len - <span class="hljs-number">1</span>; i &gt; <span class="hljs-number">0</span>; i--)&#123;<br>            	snake.x[i] = snake.x[i<span class="hljs-number">-1</span>];<br>                snake.y[i] = snake.y[i<span class="hljs-number">-1</span>];<br>            &#125;<br>            <span class="hljs-comment">// 将食物作为蛇头</span><br>            snake.x[<span class="hljs-number">0</span>] = food.x;<br>            snake.y[<span class="hljs-number">0</span>] = food.y;<br>            randomFoodPosition();<br>            drawFood();<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="3-7-判断游戏结束"><a href="#3-7-判断游戏结束" class="headerlink" title="3.7 判断游戏结束"></a>3.7 判断游戏结束</h2><p>当蛇头碰到边界或自己的蛇身游戏则结束，因为蛇身是跟着蛇头走的，所以我们只需要判断蛇头就行了。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs c"><br><span class="hljs-type">bool</span> <span class="hljs-title function_">gameover</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt; snake.len; i++)			<span class="hljs-comment">// 蛇头碰到蛇身</span><br>    	<span class="hljs-keyword">if</span>(snake.x[<span class="hljs-number">0</span>] == snake.x[i] &amp;&amp; snake.y[<span class="hljs-number">0</span>] == snake.y[i])<br>                <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    <span class="hljs-keyword">if</span>(snake.x[<span class="hljs-number">0</span>] &lt; <span class="hljs-number">2</span> || snake.x[<span class="hljs-number">0</span>] &gt; MAP_WIDTH - <span class="hljs-number">2</span>) 	<span class="hljs-comment">// 蛇头超出了左/右边界</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    <span class="hljs-keyword">if</span>(snake.y[<span class="hljs-number">0</span>] &lt; <span class="hljs-number">0</span> || snake.y[<span class="hljs-number">0</span>] &gt; MAP_HEIGHT - <span class="hljs-number">1</span>)	<span class="hljs-comment">// 蛇头超出了上/下边界</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="4-整合所有部分"><a href="#4-整合所有部分" class="headerlink" title="4. 整合所有部分"></a>4. 整合所有部分</h1><hr>
<p>将上面所有的部分整合起来，我们在 main 主函数里写游戏的逻辑：<br>代码关键部分：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">/*---------- 初始化游戏信息 ------------*/</span><br><span class="hljs-type">void</span> <span class="hljs-title function_">init</span><span class="hljs-params">()</span>&#123;<br>	hideCursor();				<span class="hljs-comment">// 隐藏光标 </span><br>	snake.len = <span class="hljs-number">1</span>;				<span class="hljs-comment">// 默认只有一个蛇头 </span><br>    snake.x[<span class="hljs-number">0</span>] = MAP_WIDTH / <span class="hljs-number">2</span>;<br>    snake.y[<span class="hljs-number">0</span>] = MAP_HEIGHT / <span class="hljs-number">2</span>;<br>    snake.speed = <span class="hljs-number">1</span>;			<br>    snake.direction = D_RIGHT;	<span class="hljs-comment">// 初始化贪吃蛇方向 向右 </span><br>    randomFoodPosition();		<span class="hljs-comment">// 产生随机食物 </span><br>    					 <br>    drawMap();					<span class="hljs-comment">// 绘制边界</span><br>    <br>    drawFood();					<span class="hljs-comment">// 绘制食物</span><br>     <br>    drawSnake();				<span class="hljs-comment">// 绘制蛇</span><br>    <br>&#125;<br><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">()</span>&#123;<br>    init();<br>	<span class="hljs-keyword">while</span> (!gameover())&#123;<br>		gotoxy(MAP_WIDTH +<span class="hljs-number">5</span>, <span class="hljs-number">0</span>);			<span class="hljs-comment">// 显示得分 </span><br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;得分: %d&quot;</span>, snake.len - <span class="hljs-number">1</span>);<br>        <span class="hljs-comment">// 判断按键</span><br>        <span class="hljs-type">int</span> keydown = keyDown();<br>        <span class="hljs-keyword">if</span>(keydown != <span class="hljs-number">-1</span>)<br>        &#123;<br>        	snake.direction = <span class="hljs-type">char</span>(keydown);<br>        &#125;<br>        snakeEatenFood();<br>		move();<br>        Sleep(<span class="hljs-number">100</span> / snake.speed);				<span class="hljs-comment">// 延迟</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>全部代码请参考 Gitee 网址：<a target="_blank" rel="noopener" href="https://gitee.com/ccuni/c-simple-game-demo/blob/master/%E8%B4%AA%E5%90%83%E8%9B%87/snake.c">C语言实现贪吃蛇</a></p>
<p>最终运行效果：</p>
<p><img src="https://img-blog.csdnimg.cn/09d16d4b89a6499da84a63f5d2db1f0d.gif#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h1><hr>
<p>相信通过本次的实践，能提升你对C语言编程的熟练度，关于这个小游戏其实还有许多可拓展的地方，比如设计一个游戏初始界面，用户可以选择”开始游戏”、”游戏说明”、”游戏设置”  等等，在游戏界面上我使用了最普通的光标移动 加 printf 打印的方式，如果你想要更好看的游戏界面，比如添加一些图片，可以了解一下 <a target="_blank" rel="noopener" href="https://easyx.cn/">EasyX</a> 这个图形库。</p>
<blockquote>
<p>EasyX Graphics Library 是针对 Visual C++ 的免费绘图库，支持 VC6.0 ~ VC2022，简单易用，学习成本极低，应用领域广泛。目前已有许多大学将 EasyX 应用在教学当中。</p>
</blockquote>
<p>不过 EasyX 是基于 C++ 语言的拓展图形库，如果你的学校是要求使用 C语言进行课程设计的话，需要考虑编程语言不同的问题哟~</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/C%E8%AF%AD%E8%A8%80/" class="category-chain-item">C语言</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/C%E8%AF%AD%E8%A8%80%E5%B0%8F%E6%B8%B8%E6%88%8F/">#C语言小游戏</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析</div>
      <div>http://example.com/2022/08/21/C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年8月21日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/08/22/Node%20%E7%AC%94%E8%AE%B01%20_%20%E5%B8%B8%E7%94%A8%E5%86%85%E7%BD%AE%20API%20_%20%E6%A8%A1%E5%9D%97%E5%8C%96%E7%BC%96%E7%A8%8B%20_%20%E8%87%AA%E5%AE%9A%E4%B9%89%20npm%E5%8C%85%E5%B9%B6%E5%8F%91%E5%B8%83%E5%88%B0%E5%AE%98%E6%96%B9%20_%20Express%20%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8%20_%20Node%20%E8%A7%A3%E5%86%B3%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%20_%20Node%20%E6%93%8D%E4%BD%9C%20MySQL/" title="Node 笔记1 _ 常用内置 API _ 模块化编程 _ 自定义 npm包并发布到官方 _ Express 模块的使用 _ Node 解决跨域问题 _ Node 操作 MySQL">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Node 笔记1 _ 常用内置 API _ 模块化编程 _ 自定义 npm包并发布到官方 _ Express 模块的使用 _ Node 解决跨域问题 _ Node 操作 MySQL</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/08/19/Vue2%20%E5%BC%80%E5%8F%91%E6%80%BB%E7%BB%93%20axios%20%E4%BA%8C%E6%AC%A1%E5%B0%81%E8%A3%85%20_%20%E8%AF%B7%E6%B1%82%E3%80%81%E5%93%8D%E5%BA%94%E3%80%81%E6%B8%B2%E6%9F%93%E7%9A%84%E5%A4%A7%E8%87%B4%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90/" title="Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析">
                        <span class="hidden-mobile">Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
